﻿// ------------------------------------------------------------------------------------------------
//  <copyright file="Matrix.cs" company="Iveely">
//    Copyright (c) Iveely Liu.  All rights reserved.
//  </copyright>
//  
//  <Create Time>
//    03/02/2013 21:59 
//  </Create Time>
//  
//  <contact owner>
//    liufanping@iveely.com 
//  </contact owner>
//  -----------------------------------------------------------------------------------------------

#region

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using IveelySE.Common;
using IveelySE.Config;

#endregion

namespace IveelySE.Spider
{
    /// <summary>
    ///   逆向邻接矩阵(用于计算PageRank)
    /// </summary>
    [Serializable]
    public class Matrix
    {
        /// <summary>
        ///   矩阵内容（用于记录矩阵关系）
        /// </summary>
        private static Hashtable Content = new Hashtable();

        /// <summary>
        ///   主键(用于记录名称以及权值)
        /// </summary>
        private static Hashtable Elist = new Hashtable();

        /// <summary>
        ///   增加矩阵元素
        /// </summary>
        /// <param name="from"> 初始URL </param>
        /// <param name="to"> 通过初始URL找到的其余的URL集合 </param>
        public static void Add(string from, IEnumerable<Uri> to)
        {
            //如果列表集中从未包含
            if(!Elist.Contains(from))
            {
                Elist.Add(from, 1.0/10000000);
                Content.Add(from, "");
            }
            foreach(Uri t in to)
            {
                //如果URL也没有包含过
                if(!Elist.Contains(t.ToString()))
                {
                    Content.Add(t.ToString(), from + "|");
                    Elist.Add(t.ToString(), 1.0/10000000);
                }
                else
                {
                    string temp = Content[t.ToString()].ToString();
                    temp += from + "|";
                    Content[t.ToString()] = temp;
                }
            }
        }

        /// <summary>
        ///   保存记录
        /// </summary>
        public static void Save()
        {
            Serialize.Serailzable(Content, Application.GetPageRankContent());
            Serialize.Serailzable(Elist, Application.GetPageRankList());
        }

        /// <summary>
        ///   加载记录
        /// </summary>
        public static void Load()
        {
            if(File.Exists(Application.GetPageRankContent()))
            {
                Content = (Hashtable) Serialize.UnSerailzable(Application.GetPageRankContent());
            }
            if(File.Exists(Application.GetPageRankList()))
            {
                Elist = (Hashtable) Serialize.UnSerailzable(Application.GetPageRankList());
            }
        }
    }
}